package com.zs.grain.service

import android.app.AlarmManager
import android.app.PendingIntent
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.widget.Toast
import com.example.clockkotlin.databaseClockAlarm.AlarmSignal
import com.zs.grain.AlarmReceiver
import com.zs.grain.AlarmReceiver1
import com.zs.grain.AlarmReceiver2
import com.zs.grain.UVLightReceiver
import com.zs.grain.tool.clockManage.LocalDataBase
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class TimerService  @Inject constructor(
    val mContext: Context,
    val mDataService: DataService
){
    lateinit var alarmManager:AlarmManager
    lateinit var rbAlarmIntent: PendingIntent
    lateinit var volAlarmIntent: PendingIntent
    lateinit var volAlarmIntent2: PendingIntent
    lateinit var alarmIntent1: PendingIntent
    val sdFormatter = SimpleDateFormat("MM-dd HH:mm")

    private val extraTime = "time"
    private val extraId = "id"
    private val intentAction = "AlarmSignal"

    fun init(){
        alarmManager = mContext?.getSystemService(Context.ALARM_SERVICE) as AlarmManager

        sdFormatter.timeZone = TimeZone.getTimeZone("GMT+8")

        initLastAction()//存储的定时任务
    }

    private fun getPendingIntent(intent: Intent): PendingIntent {
        return PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
    }

    fun initLastAction(){
        //var settingTime:String ?= null
        val clocksArray:ArrayList<AlarmSignal> = LocalDataBase.getClocksArray()
        for(ca in clocksArray){
            if(ca.enable){
                if(ca.setting.contains("reboot")){
                    addTask("reboot",ca.time)
                }else if(ca.setting.contains("makingProduct")){
                    LocalDataBase.deleteAlarm("makingProduct")
                }else if(ca.setting.contains("waitingReboot")){
                    LocalDataBase.deleteAlarm("waitingReboot")
                }else addTask(ca.setting,ca.time)
            }
        }
    }

    fun addTask(setting:String,time:String){
        val sdFormatter = SimpleDateFormat("HH:mm")
        val clockTime: Date = sdFormatter.parse(time)
        val cal = Calendar.getInstance()
        cal.set(Calendar.HOUR_OF_DAY,clockTime.hours)
        cal.set(Calendar.MINUTE,clockTime.minutes)
        cal.set(Calendar.SECOND, 0)
        cal.set(Calendar.MILLISECOND, 0)
        val calendarNow = Calendar.getInstance()
        val currentTime = calendarNow.time
        if (cal.time.time <= currentTime.time) {
            cal.timeInMillis += TimeUnit.HOURS.toMillis(24)
        }
        sdFormatter.timeZone = TimeZone.getTimeZone("GMT+8")
        //alarmManager = mContext?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        if(setting=="reboot") {
            rbAlarmIntent = Intent(mContext, AlarmReceiver::class.java).let { intent ->
                PendingIntent.getBroadcast(mContext, 0, intent, 0)
            }
            val info = AlarmManager.AlarmClockInfo(cal.timeInMillis, rbAlarmIntent)
            alarmManager?.setAlarmClock(info,rbAlarmIntent)
        }else{
            if(setting.contains("vol1")) {
                volAlarmIntent = Intent(mContext, AlarmReceiver1::class.java).let { intent ->
                    intent.putExtra("volumn1",setting.substring(5).toInt())
                    PendingIntent.getBroadcast(mContext, 0, intent, 0)
                }
                val info = AlarmManager.AlarmClockInfo(cal.timeInMillis, volAlarmIntent)
                alarmManager?.setAlarmClock(info,volAlarmIntent)
            }
            if(setting.contains("vol2")) {
                volAlarmIntent2 = Intent(mContext, AlarmReceiver2::class.java).let { intent ->
                    intent.putExtra("volumn2",setting.substring(5).toInt())
                    PendingIntent.getBroadcast(mContext, 0, intent, 0)
                }
                val info = AlarmManager.AlarmClockInfo(cal.timeInMillis, volAlarmIntent2)
                alarmManager?.setAlarmClock(info,volAlarmIntent2)
            }
            if(setting.contains("uvlight")) {
                alarmIntent1 = Intent(mContext, UVLightReceiver::class.java).let { intent ->
                    //intent.putExtra("volumn2",setting.substring(5).toInt())
                    PendingIntent.getBroadcast(mContext, 0, intent, 0)
                }
                val info = AlarmManager.AlarmClockInfo(cal.timeInMillis, alarmIntent1)
                alarmManager?.setAlarmClock(info,alarmIntent1)
            }
        }
    }

    private fun getClockTime(time: String): Long {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, time.take(2).toInt())
        calendar.set(Calendar.MINUTE, time.takeLast(2).toInt())
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        val clockTime: Date = calendar.time

        val calendarNow = Calendar.getInstance()
        val currentTime = calendarNow.time

        if (clockTime.time > currentTime.time) {
            return clockTime.time
        } else {
            return clockTime.time + TimeUnit.HOURS.toMillis(24)
        }
    }

    private fun getIntent(time: String, id: Long): Intent {
        val intent = Intent(mContext, AlarmReceiver::class.java)
        intent.action = "$intentAction $time"
        intent.putExtra(extraTime, time)
        intent.putExtra(extraId, id)
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
        return intent
    }

    fun cancelTimer(setting:String){
        //TODO:bug1:each day work is available?
        when(setting){
            "reboot" -> {
                if(this::rbAlarmIntent.isInitialized)
                    alarmManager?.cancel(rbAlarmIntent)
            }
            "vol" -> {
                if(this::volAlarmIntent.isInitialized)
                    alarmManager?.cancel(volAlarmIntent)
                if(this::volAlarmIntent2.isInitialized)
                    alarmManager?.cancel(volAlarmIntent2)
            }
            "uvlight" -> {
                if(this::alarmIntent1.isInitialized)
                    alarmManager?.cancel(alarmIntent1)
            }
        }
//        if(setting=="reboot") {
//            alarmManager?.cancel(rbAlarmIntent)
//        }
        //alarmManager?.cancel(rbAlarmIntent)
        LocalDataBase.deleteAlarm(setting)//清除以后的自动任务
    }

    companion object {

    }
}